<template>
    <el-dialog :model-value="props.visible" title="录入半成品部件" @close="handleClose" destroy-on-close width="40%" >
        <el-form ref="recordPreparedProductFormRef" :model="recordPreparedProductFormData" >
            <el-row>
                <el-col :span="6">
                    <el-form-item label="小类">
                        <span>{{ props.data.productSubcategoryName }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="半成品名称">
                        <span>{{ props.data.specsDetail }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item prop="totalImage">
                        <div class="upload-container">
                                <el-upload
                                    ref="totleUploadRef"
                                    v-model:fileList="fileList"
                                    :action="uploadImgUrl"
                                    :headers="headers"
                                    :limit="1"
                                    @on-success="handleTotalSuccess"
                                    @before-upload="beforeTotalUpload"
                                    
                                >
                                    <el-button type="primary">点击上传文件</el-button>
                                </el-upload>
                        </div>
                        <span v-show="recordPreparedProductFormData.imageUrl">尚未上传文件</span>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="6">
                    <el-form-item label="纸张类别" prop="paperType">
                        <el-select v-model="recordPreparedProductFormData.paperType">
                            <el-option v-for="item in paperTypes" :key="item.id" :label="item.subclassName" :value="item.subclassType"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="克重" prop="weight">
                        <el-input-number v-model="recordPreparedProductFormData.weight" placeholder="g" controls-position="right">
                            <template #decrease-icon>
                                <el-icon>
                                    <Minus />
                                </el-icon>
                            </template>
                            <template #increase-icon>
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </template>
                        </el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="门幅(长)" prop="length">
                        <el-input-number v-model="recordPreparedProductFormData.length" placeholder="mm" controls-position="right">
                            <template #decrease-icon>
                                <el-icon>
                                    <Minus />
                                </el-icon>
                            </template>
                            <template #increase-icon>
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </template>
                        </el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="纸张(宽)" prop="width" >
                        <el-input-number v-model="recordPreparedProductFormData.width" placeholder="mm" controls-position="right">
                            <template #decrease-icon>
                                <el-icon>
                                    <Minus />
                                </el-icon>
                            </template>
                            <template #increase-icon>
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </template>
                        </el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="15">
                <el-col :span="6">
                    <el-form-item label="刀模拼数" prop="numberOfSets">
                        <el-input type="number" v-model.number="recordPreparedProductFormData.numberOfSets" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="拼版尺寸" prop="templateSize">
                        <el-input v-model="recordPreparedProductFormData.templateSize" placeholder="请输入" >
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="刀模编号" prop="knifeId">
                        <el-select v-model="recordPreparedProductFormData.knifeId" placeholder="请选择">
                            <el-option v-for="item in props.knifeModels" :key="item.id" :label="item.knifeName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item prop="outerWarehouseFlag" >
                        <el-checkbox v-model="recordPreparedProductFormData.outerWarehouseFlag" :true-label="1" :false-label="0" label="外协库" size="large" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-button type="success" plain @click="handleClickAddNewProcess">新增生产工序</el-button>
                    </el-col>
                </el-row>
            </el-form-item>
            <div class="flex gap-3" style="margin-bottom: 15px">
                <el-tag :class="item.workName?'':'newly-process'" v-for="(item,index) in recordPreparedProductFormData.productJoinWorks" :key="item.workProcedureId" size="large" closable @close="handleDeleteProcess(index)">{{ item.workName }}</el-tag>
                <newProcess :visible="addNewProcessVisible" :process="props.processes" @close="handleCloseAddNewProcess" @transmitProcess="handleGetNewProcess" />
            </div>
            <el-form-item label="子部件">
                <el-button type="success" plain @click="handleClickAddComponent">新增</el-button>
            </el-form-item>
            <!-- <div class="new-preparedProduct-containers">
            </div> -->
            <newComponent v-for="(item,index) in recordPreparedProductFormData.semiChildrenProductions" :key="index" :data="item" :componentType="props.componentType" @transmitData="(data:any)=>getComponentResult(index,data)" @delete="handleDeleteComponent(index)" />
            </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button  type="primary"  @click="handleSubmit" >确 定</el-button>
                <el-button @click="handleClose">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, UploadInstance, UploadProps,UploadUserFile } from 'element-plus';
import { globalHeaders } from "@/utils/request";
import newComponent from './newComponent.vue';
import newProcess from './newProcess.vue';
import { addSemiConstituteInfoApi } from '@/api/sj/warehouse/productInventory'; 
import { getSingleByTotalApi } from '@/api/sj/warehouse/typeManagement';

interface componentVO{
    componentName?: string;
    componentType?: string | number;
}
interface processVO{
    workProcedureId?: string | number;
    workName?: string;
}
interface recordPreparedProductVO{
    imageUrl?: string;
    paperType?: string;
    weight?: number;
    width?: number;
    length?: number;
    knifeId?: string;
    knifeName?: number;
    numberOfSets?: number;
    templateSize?: string;
    outerWarehouseFlag?: number;
    semiChildrenProductions: componentVO[],
    productJoinWorks: processVO[]
}
const props = defineProps(['visible','data','paper','processes','componentType','knifeModels']);
const emits = defineEmits(['close','submit']);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const totleUploadRef = ref<UploadInstance>();
const recordPreparedProductFormRef = ref<FormInstance>();
const shouldSubmit = ref(true);
//纸张类型大类(外协库)
const assistType = 'auxiliary_material_assist';
const paperTypes = ref<any[]>([]);

const recordPreparedProductFormData = ref<recordPreparedProductVO>({
    imageUrl: undefined,
    paperType: undefined,
    weight: undefined,
    length: undefined,
    width: undefined,
    knifeId: undefined,
    knifeName: undefined,
    numberOfSets: undefined,
    templateSize: undefined,
    outerWarehouseFlag: 1,
    semiChildrenProductions:[],
    productJoinWorks: []
});
const fileList = ref<UploadUserFile[]>([])

const addNewProcessVisible = ref(false);

const totalImageName = ref();

const handleTotalSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // console.log(URL.createObjectURL(uploadFile.raw!));
    console.log(response);
    //@ts-ignore
    recordPreparedProductFormData.value.imageUrl = URL.createObjectURL(uploadFile.raw!);
    totalImageName.value = response;
    shouldSubmit.value = false;
};

const beforeTotalUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片格式与要求不符')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片不可超过 5MB!')
        return false
    }
    return true
};

/** 获取纸张类型 */
watch(()=>props.visible, async (visible)=>{
    if(visible){
        const {code, data} = await getSingleByTotalApi(assistType);
        if(code == 200){
            paperTypes.value = data;
        };
    };
},{deep: true});

/** 点击删除工序 */
const handleDeleteProcess = (index: number)=>{
    recordPreparedProductFormData.value?.productJoinWorks.splice(index,1);
};

/** 点击新增生产工序 */
const handleClickAddNewProcess = ()=>{
    addNewProcessVisible.value = true;
};

/**关闭新增生产工序 */
const handleCloseAddNewProcess = ()=>{
    addNewProcessVisible.value = false;
};

/** 接受新步骤 */
const handleGetNewProcess = (newProcess: any)=>{
    let sort = recordPreparedProductFormData.value?.productJoinWorks.length + 1;
    const newProcessData = {
        ...newProcess,
        sort: sort
    };
    recordPreparedProductFormData.value?.productJoinWorks.push(newProcessData);
};

/** 点击新增部件 */
const handleClickAddComponent = ()=>{
    const componentData:componentVO = {
        componentType: undefined,
        componentName: undefined
    };
    recordPreparedProductFormData.value.semiChildrenProductions.push(componentData);
};

/** 接受新增部件的信息 */
const getComponentResult = (index: number,result: any) => {
    recordPreparedProductFormData.value.semiChildrenProductions[index] = {...result};
};

/** 删除部件 */
const handleDeleteComponent = (index: number) => {
    recordPreparedProductFormData.value.semiChildrenProductions.splice(index,1);
};

const handleSubmit = async () => {
    const submitData = {
        ...recordPreparedProductFormData.value,
        productSubcategoryType: props.data.productCategoriesType,
        semiId: props.data.id,
        //@ts-ignore
        imageUrl: fileList.value[0]?.response?.data?.url
    };
    const {code} = await addSemiConstituteInfoApi(submitData);
    if(code == 200){
        emits('submit',true);
        handleClose();
    }else{
        emits('submit',false);
    }
};

const handleClose = ()=>{
    recordPreparedProductFormRef.value?.resetFields();
    recordPreparedProductFormData.value.semiChildrenProductions = [];
    addNewProcessVisible.value = false;
    fileList.value = [];
    totleUploadRef.value?.clearFiles();
    shouldSubmit.value = true;
    emits('close');
    
};
</script>

<style lang="scss" scoped>
.el-form {
    height: 300px;
}
.upload-container{
    div{
        display: flex;
        justify-content: flex-start;
    }
}
// ::v-deep(.el-upload-list){
//     float: right;
// }
.new-preparedProduct-containers{
    width: 100%;
    overflow-x: scroll;
    margin-top:20px;
    display: flex;
    padding-bottom: 10px;
    .new-preparedProduct-container:not(:first-child){
        margin-left: 10px;
    }
    .new-preparedProduct-container{
        width: 180px;
    }
    .el-input{
        margin-top:5px;
    }
    .new-preparedProduct-number{
        display: block;
        margin-top:5px;
    }
}
.el-upload {
    
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    border: 1px dashed var(--el-border-color);
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
.newly-process{
    cursor: pointer;
}
.dialog-footer{
    display: flex;
    justify-content: center;
}
</style>